﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Commands
{
    public static class  FilesHelper
    {
        //internal static void FilesHelper()
        //{
        //    // TODO get user default folder.
        //}

        /// <summary>
        /// Initialization. 
        /// </summary>
        internal static void Init(string defaultDownloadDir)
        {
            DefaultDownloadDir = string.IsNullOrEmpty(defaultDownloadDir) ? 
                _GetSystemDownloadFolder()
                : defaultDownloadDir;
        }

        private static string _GetSystemDownloadFolder()
        {
            try
            {
                IntPtr outPath;
                int result = SHGetKnownFolderPath(new Guid("{374DE290-123F-4565-9164-39C4925E467B}"),
                    (uint)0x00000400, new IntPtr(0), out outPath);
                return Path.Combine(Marshal.PtrToStringUni(outPath), "RemoteCommands");
            }
            catch (Exception)
            {
                return _GetTempFolderName();
            }
        }

        [DllImport("Shell32.dll")]
        private static extern int SHGetKnownFolderPath(
            [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken,
            out IntPtr ppszPath);

        public static string DefaultDownloadDir
        {
            get;
            private set;
        }

        public static string ApplicationTempDirectory
        {
            get
            {
                return "Temp";
            }
        }

        public static string GetTempFilePath(string filename)
        {
            return Path.Combine(_GetTempFolderName(), filename);
        }

        public static string PrepareTempZipFilePath(string filename)
        {
            var zipDirPath = Path.Combine(_GetTempFolderName(), ZIP);

            if (!Directory.Exists(zipDirPath))
                Directory.CreateDirectory(zipDirPath);

            return Path.Combine(zipDirPath, filename + ".zip");
        }

        internal static string GetDownloadFilePath(string directory, string fileName, string url)
        {
            var folder = directory != null ? directory : DefaultDownloadDir;
            var file = fileName != null ? fileName : _GetFileNameFromURL(url);
            return Path.Combine(folder, file);
        }

        private static string _GetFileNameFromURL(string url)
        {
            Uri uri = new Uri(url);
            return Path.GetFileName(uri.LocalPath);
        }

        internal static string SaveToTextFile(string name, string content)
        {
            var filePath = GetTempFilePath(name + ".txt");

            using (var writer = new StreamWriter(filePath))
            {
                writer.Write(content);
            }

            return filePath;
        }

        internal static string GetAttachmentsFolder()
        {
            var path = Path.Combine(_GetTempFolderName(), GetSafeFilename(DateTime.Now.ToShortDateString())) + '.';
            
            var i = 0;
            string temp;

            do
            {
                temp = path + i++;
            }
            while (Directory.Exists(temp)) ;

            Directory.CreateDirectory(temp);

            return temp;
        }

        private static string GetSafeFilename(string folder)
        {
            return string.Join("_", folder.Split(Path.GetInvalidPathChars()));
        }

        // TEST
        internal static void CleanUpFile(string filePath)
        {
            File.Delete(filePath);

            var directory = new FileInfo(filePath).Directory;
            try
            {
                directory.Delete();
            }
            // If folder isn't empty - do nothing.
            catch (IOException ex) { }
        }

        internal static void CleanUpFiles(IEnumerable<string> filesPaths)
        {
            foreach (var path in filesPaths)
                CleanUpFile(path);
        }
        
        private static string _GetTempFolderName()
        {
            var tempFolder = ApplicationTempDirectory;

            if (!Directory.Exists(tempFolder))
                Directory.CreateDirectory(tempFolder);

            return tempFolder;
        }

        /// <summary>
        /// TODO
        /// </summary>
        private static bool _PathCanExist(string folderName)
        {
            if (string.IsNullOrEmpty(folderName))
                return false;

            return true;
        }

        private const string ZIP = @"ZIP";
    }
}
